package com.daxia.bumall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.bumall.dao.DesignerInfoDAO;
import com.daxia.bumall.dto.DesignerInfoDTO;
import com.daxia.bumall.model.DesignerInfo;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.BeanMapper;

@Service
public class DesignerInfoService {
	
	@Autowired
	private DesignerInfoDAO designerInfoDAO;
	
	public List<DesignerInfoDTO> find(DesignerInfoDTO query, Page page) {
		List<DesignerInfo> models = designerInfoDAO.find(query, page);
		List<DesignerInfoDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<DesignerInfoDTO> findAll() {
		return this.find(new DesignerInfoDTO(), null);
	}
	
	public List<DesignerInfoDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new DesignerInfoDTO(), page);
	}
	
	public Long create(DesignerInfoDTO dto) {
		DesignerInfo model = new DesignerInfo();
		toModel(model, dto);
		return designerInfoDAO.create(model);
	}
	
	public DesignerInfoDTO load(Long id) {
	    DesignerInfo model = designerInfoDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(DesignerInfoDTO dto) {
		DesignerInfo model = designerInfoDAO.load(dto.getId());
		toModel(model, dto);
		designerInfoDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				designerInfoDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public DesignerInfoDTO findOne(DesignerInfoDTO query) {
		DesignerInfo model = designerInfoDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<DesignerInfoDTO> toDTOs(List<DesignerInfo> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<DesignerInfoDTO>(0);
		}
		List<DesignerInfoDTO> dtos = new ArrayList<DesignerInfoDTO>(models.size());
		for (DesignerInfo model : models) {
	        DesignerInfoDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private DesignerInfoDTO toDTO(DesignerInfo model) {
		if (model == null) {
			return null;
		}
		DesignerInfoDTO dto = BeanMapper.map(model, DesignerInfoDTO.class);
		
		return dto;
	}
	
	private void toModel(DesignerInfo model, DesignerInfoDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<DesignerInfo> toModels(List<DesignerInfoDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<DesignerInfo>(0);
		}
		List<DesignerInfo> models = new ArrayList<DesignerInfo>(dtos.size());
		for (DesignerInfoDTO dto : dtos) {
	        DesignerInfo model = new DesignerInfo();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
